#include "gui.h"
#include "input.h"

button::button(guimngr* _parent,xml_node &_node):gui_element(_parent,_node)
{
	m_x = _node.attr_float("x");
	m_y = _node.attr_float("y");
	m_w = _node.attr_float("w");
	m_h = _node.attr_float("h");
	float tx = _node.attr_float("tx");
	float ty = _node.attr_float("ty");
	float tw = _node.attr_float("tw");
	float th = _node.attr_float("th");
	m_text_dx = _node.attr_float("text_dx");
	m_text_dy = _node.attr_float("text_dy");
	char* tex = _node.attr_str("texture","empty.png");
	m_text = _node.attr_str("text","");
	m_texture = m_parent->m_resmngr->get_texture(tex);
	m_sprite = sprite(m_x,m_y,0.0f,m_w,m_h,m_texture,tx,ty,tw,th);
}

button::~button()
{
}

bool button::intersect(float _x, float _y)
{
	if(_x>m_x&&_x<(m_x+m_w)&&_y>m_y&&_y<(m_y+m_h))
	{
		m_sprite.set_color(color(1.0f,1.0f,1.0f,1.0f));
		return true;
	}
	else
	{
		m_sprite.set_color(color(0.8f,0.8f,0.8f,1.0f));
		return false;
	}
}

void button::draw()
{
	m_sprite.draw();
	m_parent->get_font()->print(m_x+m_text_dx,m_y+m_text_dy,0.0f,m_text.c_str());
}

guimngr::guimngr(gui_callback _callback,void* _cls,xml_node& _node)
{
	m_callback = _callback;
	m_cls = _cls;

	m_resmngr = new resourcemngr();

	char* fnt = _node["font"].attr_str("name");
	float r = _node["font"].attr_float("r");
	float g = _node["font"].attr_float("g");
	float b = _node["font"].attr_float("b");
	float a = _node["font"].attr_float("a");
	float size = _node["font"].attr_float("size");

	m_font = m_resmngr->get_font(fnt);

	for(u32 i=0;i<_node.child_count();i++)
	{
		string name = _node[i].name();
		if(name=="button")
		{
			button* b = new button(this,_node[i]);
			m_elements.push_back(b);
		}
	}
}

guimngr::~guimngr()
{
	list<gui_element*>::iterator i;
	for(i=m_elements.begin();i!=m_elements.end();i++)
	{
		delete (*i);
	}
	m_elements.clear();
	delete m_resmngr;
}

void guimngr::set_mouse_pos(float _x, float _y)
{
	m_mx = _x;
	m_my = _y;
}

void guimngr::update()
{
	list<gui_element*>::iterator i;
	for(i=m_elements.begin();i!=m_elements.end();i++)
	{
		if((*i)->intersect(m_mx,m_my))
		{
			if(input::get_inst().is_mouse_key(0))
			{
				if(m_callback)
				{
					gui_event e;
					e.id = (*i)->get_id();
					e.data = "pressed";
					m_callback(m_cls,e);
				}
			}
		}
	}
}

void guimngr::draw()
{
	list<gui_element*>::iterator i;
	for(i=m_elements.begin();i!=m_elements.end();i++)
	{
		(*i)->draw();
	}
}